﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using Waker.Common;

namespace Waker.SystemSetting
{
    public partial class FormPermission : Base.FormBasePop
    {
        private int _GroupId;
        public FormPermission(int groupId, string groupName, bool isUser)
        {
            InitializeComponent();
            _GroupId = groupId;
            this.Text = string.Format("权限组[{0}]的权限管理", groupName);
            xtraTabControl1.SelectedTabPageIndex = isUser ? 1 : 0;
        }

        private void FormPermission_Load(object sender, EventArgs e)
        {
            BindTreeList();
            BindGrid();
        }

        private void BindTreeList()
        {
            var dt = new BAL.BAL_SystemSetting().GetPermissionGroupByGroupId(_GroupId);
            if (dt == null || dt.Rows.Count < 1)
                return;
            //treeList1.DataSource = dt;
            //treeList1.ParentFieldName = "ParentCode";
            //treeList1.KeyFieldName = "FunCode";
            //treeList1.ExpandAll();
            var drsParent = dt.Select("ISNULL(ParentCode,'')=''", "FunSort ASC");
            if (drsParent.Length < 1)
                return;
            var indexImageSelect = 23;
            var indexImageState = -1;
            var nodeRoot = treeList1.AppendNode(new object[] { "所有菜单" }, 0, -1, indexImageSelect, indexImageState);
            int countAll = 0;
            foreach (var drParent in drsParent)
            {
                var nodeParent = treeList1.AppendNode(new object[] { drParent["FunName"] }, 0, drParent["ImageIndex"] == DBNull.Value ? -1 : Convert.ToInt32(drParent["ImageIndex"]), indexImageSelect, indexImageState);
                //nodeParent.SetValue(this.treeColFunCode, drParent["FunCode"]);
                //nodeParent.SetValue(this.treeColFunName, drParent["FunName"]);
                var drs = dt.Select(string.Format("ParentCode='{0}'", drParent["FunCode"]), "FunSort ASC");
                if (drs.Length < 1)
                    continue;
                int count = 0;
                foreach (var dr in drs)
                {
                    var node = treeList1.AppendNode(new object[] { dr["FunName"] }, nodeParent.Id, drParent["ImageIndex"] == DBNull.Value ? -1 : Convert.ToInt32(drParent["ImageIndex"]), indexImageSelect, indexImageSelect);
                    //node.SetValue(this.treeColFunCode, dr["FunCode"]);
                    node.Tag = dr["FunCode"];
                    node.SetValue(this.treeColFunName, dr["FunName"]);
                    var isCheck = dr["IsCheck"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsCheck"]);
                    node.Checked = isCheck;
                    //nodeParent.Nodes.Add(nodeParent);
                    if (isCheck)
                        count++;
                }
                if (drs.Length == count)
                {
                    nodeParent.Checked = true;
                    countAll++;
                }
                if (countAll == drsParent.Length)
                    nodeRoot.Checked = true;
                //treeList1.Nodes.Add(nodeParent);
            }
            treeList1.ExpandAll();
        }
        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            //从子到父
            if (!e.Node.HasChildren)
            {
                if (!e.Node.ParentNode.HasChildren)
                    return;
                int count = 0;
                foreach (TreeListNode node in e.Node.ParentNode.Nodes)
                {
                    if (node.Checked)
                        count++;
                }
                e.Node.ParentNode.Checked = count == e.Node.ParentNode.Nodes.Count;
                count = 0;
                foreach (TreeListNode node in e.Node.RootNode.Nodes)
                {
                    if (node.Checked)
                        count++;
                }
                e.Node.RootNode.Checked = count == e.Node.RootNode.Nodes.Count;
                return;
            }
            //从父到子
            foreach (TreeListNode nodeParent in e.Node.Nodes)
            {
                nodeParent.Checked = e.Node.Checked;
                if (!nodeParent.HasChildren)
                    continue; ;
                foreach (TreeListNode node in nodeParent.Nodes)
                    node.Checked = e.Node.Checked;
            }
        }
        private void BindGrid()
        {
            var dt = new BAL.BAL_SystemSetting().GetPermissionUserByGroupId(_GroupId);
            this.gridControl1.DataSource = dt;
        }
        protected override void FormSave()
        {
            var listFunCode = new List<string>();
            foreach (TreeListNode nodeParent in treeList1.Nodes[0].Nodes)
            {
                foreach (TreeListNode node in nodeParent.Nodes)
                {
                    if (!node.Checked || node.Tag == null || listFunCode.Contains(node.Tag.ToString()))
                    {
                        continue;
                    }
                    listFunCode.Add(node.Tag.ToString());
                }
            }

            var listUser = new List<string>();
            var dt = this.gridControl1.DataSource as DataTable;
            if (dt != null && dt.Rows.Count > 0)
            {
                dt.Select("IsCheck=1")
                    .Where(dr => dr["UserCode"] != DBNull.Value && !listUser.Contains(dr["UserCode"].ToString()))
                    .ToList()
                        .ForEach(dr =>
                        {
                            listUser.Add(dr["UserCode"].ToString());
                        });
            }
            var isOk = new BAL.BAL_SystemSetting().SavePermission(listFunCode, listUser, _GroupId);
            if (isOk)
            {
                UI.ShowInfo("保存成功");
                //this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                UI.ShowError("保存失败");
            }
        }
    }
}